import React, { useEffect, useState, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Avatar } from 'antd';
import defaultAvatar from '@/assets/orgTree_userAvatar.png';

const colorList = ['#ff9f00'];

const AvatarComponent = ({ src, alt, ...props }) => {
    const [avatar, setAvatar] = useState(null);
    const [isError, setIsError] = useState(false);

    useEffect(() => {
        if (src) {
            setAvatar(src);
        } else {
            setAvatar(alt.slice(0, 1).toUpperCase());
        }
    }, [alt, src]);

    const customStyle = useMemo(
        () => ({ color: '#FFF', backgroundColor: colorList[Math.floor(Math.random() * (colorList.length - 1))] }),
        []
    );

    const handlerError = () => {
        if (alt) {
            setAvatar(alt.slice(0, 1));
            setIsError(true);
        }
    };

    return (
        <Avatar
            src={src && !isError ? avatar : defaultAvatar}
            onError={handlerError}
            style={src && !isError ? null : customStyle}
            {...props}
        >
            {avatar}
        </Avatar>
    );
};

AvatarComponent.propTypes = {
    src: PropTypes.string,
    alt: PropTypes.string,
    props: PropTypes.object
};

AvatarComponent.defaultProps = {
    src: '',
    alt: '',
    props: undefined
};

export default AvatarComponent;
